package com.ming.tflitesingleblur.segment.operator;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.support.annotation.NonNull;

import org.tensorflow.lite.support.image.ImageOperator;
import org.tensorflow.lite.support.image.TensorImage;

/**
 * Created by glue.wang on 2019/12/5.
 * e-mail:miniminiming@qq.com
 *
 * 原本的有问题，旋转角度是反的，导致最后输入模型的图片也是反的
 * 这里只改了一下旋转的方向，-90改成了90  测试手机为vivo V1818A
 */
public class Rot90Operator implements ImageOperator {

    private final int numRotation;

    public Rot90Operator() {
        this(1);
    }

    public Rot90Operator(int k) {
        this.numRotation = k % 4;
    }

    @NonNull
    public TensorImage apply(@NonNull TensorImage image) {
        Bitmap input = image.getBitmap();
        if (this.numRotation == 0) {
            return image;
        } else {
            int w = input.getWidth();
            int h = input.getHeight();
            Matrix matrix = new Matrix();
            matrix.postTranslate((float)w * 0.5F, (float)h * 0.5F);
            matrix.postRotate((float)(90 * this.numRotation));
            int newW = this.numRotation % 2 == 0 ? w : h;
            int newH = this.numRotation % 2 == 0 ? h : w;
            matrix.postTranslate((float)newW * 0.5F, (float)newH * 0.5F);
            Bitmap output = Bitmap.createBitmap(input, 0, 0, w, h, matrix, false);
            image.load(output);
            return image;
        }
    }

    @Override
    public int getOutputImageWidth(int i, int i1) {
        return 0;
    }

    @Override
    public int getOutputImageHeight(int i, int i1) {
        return 0;
    }

    @Override
    public PointF inverseTransform(PointF pointF, int i, int i1) {
        return null;
    }
}
